import sys
import asyncio
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget
import aiohttp
from asyncqt import QEventLoop  # 用于桥接 asyncio 和 PyQt5 事件循环[3](@ref)

class AsyncRequestWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("异步请求示例")
        self.resize(400, 200)
        
        # UI 组件
        self.label = QLabel("点击按钮获取数据", self)
        self.button = QPushButton("发送请求", self)
        self.button.clicked.connect(self.start_request)
        
        # 布局
        layout = QVBoxLayout()
        layout.addWidget(self.label)
        layout.addWidget(self.button)
        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)
    
    async def fetch_data(self):
        """异步发送网络请求"""
        url = "http://www.ifeng.com"
        async with aiohttp.ClientSession() as session:
            try:
                async with session.get(url) as response:
                    if response.status == 200:
                        data = await response.json()
                        return f"用户信息：{data['login']}，头像：{data['avatar_url']}"
                    else:
                        return f"请求失败：{response.status}"
            except Exception as e:
                return f"错误：{str(e)}"
    
    def start_request(self):
        """启动异步任务"""
        asyncio.create_task(self.perform_request())
    
    async def perform_request(self):
        """执行异步操作并更新 UI"""
        result = await self.fetch_data()
        # 通过信号槽机制更新 UI（需在主线程执行）
        self.label.setText(result)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    loop = QEventLoop(app)  # 创建 asyncio 兼容的事件循环[3](@ref)
    asyncio.set_event_loop(loop)
    
    window = AsyncRequestWindow()
    window.show()
    
    with loop:  # 启动事件循环
        sys.exit(loop.run_forever())